package com.huika.dealontop.control.login.activity;

import android.annotation.TargetApi;
import android.graphics.Color;
import android.os.Build;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.Response;
import com.google.gson.reflect.TypeToken;
import com.hk.app.android.lib.encrypt.MD5Security;
import com.huika.dealontop.R;
import com.huika.dealontop.config.Constants;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.login.event.LoginEvent;
import com.huika.dealontop.support.domain.FindPwdCodeBean;
import com.huika.dealontop.support.domain.FindPwdVerfyBean;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.TitleBarHelper;
import com.huika.dealontop.views.cleardit.ClearableEditText;
import com.huika.huikalib.utils.StringUtils;

import de.greenrobot.event.EventBus;

public class FindPwdActivity extends BaseAct {
    private ClearableEditText etPhone;
    private ClearableEditText etVerfy;
    private TextView btnVerfy;
    private Button btnNext;


    private String phone;
    private int mGetPhoneMail = 1;
    private TextView mSelectMail;
    private TextView mSelectPhone;
    private View mViewPhone;
    private View mViewMail;
    private ClearableEditText mPwd;
    private ClearableEditText mPwdAgain;
    private CountDownTimer mTimeStart;

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_find_pwd);
        EventBus.getDefault().register(this);
    }

    public void onEventMainThread(LoginEvent loginEvent) {
        if (loginEvent.getLoginStatus() == 1) {
            this.finish();
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void initWidget() {
        TitleBarHelper titleBarHelper = new TitleBarHelper(this, -1, -1, R.string.title_findpwd);
        titleBarHelper.setOnLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                aty.finish();
            }
        });
        mSelectMail = (TextView) findViewById(R.id.register_select_mail);
        mSelectPhone = (TextView) findViewById(R.id.register_select_phone);
        mViewPhone = findViewById(R.id.register_view_phone);
        mViewMail = findViewById(R.id.register_view_mail);

        //手机,邮箱账号
        etPhone = (ClearableEditText) findViewById(R.id.et_phone_afp);
        //密码
        mPwd = (ClearableEditText) findViewById(R.id.et_pwd_asn);
        //再输入一次密码
        mPwdAgain = (ClearableEditText) findViewById(R.id.et_conpwd_asn);
        //验证码
        etVerfy = (ClearableEditText) findViewById(R.id.et_verfy_afp);
        //获取验证码按钮
        btnVerfy = (TextView) findViewById(R.id.btn_verfy_ar);
        //找回账号
        btnNext = (Button) findViewById(R.id.btn_next_afp);
        setVerfyEt(false);
        initLiseter();
        //phoneValidator = new EditTextValidator(this).add(new ValidationModel(etPhone, new PhoneNumberValidation())).execute();
        //editTextValidator = new EditTextValidator(this).add(new ValidationModel(etVerfy, new VerifyNumberValidation())).execute();
        //手机内容监听器 需要了解泰国的手机号码.
        etPhone.addTextChangedListener(new TextWatcher() {
                                           @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                                           @Override
                                           public void onTextChanged(CharSequence s, int start, int before, int count) {

                                           }

                                           CharSequence ms = null;

                                           @Override
                                           public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                                               ms = s;
                                           }

                                           @Override
                                           public void afterTextChanged(Editable s) {
                                               int t = ms.length();
                                               if (mGetPhoneMail == 1) {
                                                   if (t > 10) {
                                                       s.delete(t - 1, t);

                                                       etPhone.setText(s);
                                                       etPhone.setSelection(t - 1);
                                                   }
                                               }
                                           }


                                       }

        );

    }

    private void initLiseter() {
        mSelectMail.setOnClickListener(this);
        mSelectPhone.setOnClickListener(this);
        btnVerfy.setOnClickListener(this);
        btnNext.setOnClickListener(this);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.btn_verfy_ar:
                verfy();
                break;
            case R.id.btn_next_afp:
                next();
                break;
            case R.id.register_select_phone:
                //1是手機
                mGetPhoneMail = 1;
                selectPhone();
                etPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
                break;
            case R.id.register_select_mail:
                //2是郵箱
                mGetPhoneMail = 2;
                selectMail();
                etPhone.setInputType(InputType.TYPE_CLASS_TEXT);
                break;

            default:
                break;
        }
    }


    private void selectMail() {

        //
        mSelectMail.setTextColor(getResources().getColor(R.color.color_fd702b));
        mViewMail.setBackgroundResource(R.mipmap.register_line_yellow_xian);
        //
        mSelectPhone.setTextColor(Color.BLACK);
        mViewPhone.setBackgroundResource(R.mipmap.register_line_white_xian);
        etPhone.setHint(getResources().getString(R.string.register_e_mail));
        etPhone.setText("");
        etVerfy.setText("");
        mPwd.setText("");
        mPwdAgain.setText("");

        if (mTimeStart != null) {
            mTimeStart.cancel();
            mTimeStart.onFinish();
        }

    }


    private void selectPhone() {

        mSelectPhone.setTextColor(getResources().getColor(R.color.color_fd702b));
        mViewPhone.setBackgroundResource(R.mipmap.register_line_yellow_xian);
        //
        mSelectMail.setTextColor(Color.BLACK);
        mViewMail.setBackgroundResource(R.mipmap.register_line_white_xian);

        etPhone.setHint(getResources().getString(R.string.register_thailand_phonenumber));
        etPhone.setText("");
        etVerfy.setText("");
        mPwd.setText("");
        mPwdAgain.setText("");

        if (mTimeStart != null) {
            mTimeStart.cancel();
            mTimeStart.onFinish();
        }
    }

    private boolean isPhoneMail() {
        String tempStr = UIUtils.getString(R.string.register_thailand_phonenumber);
        if (tempStr.equals(etPhone.getHint())) {
            return true;
        }
        return false;
    }

    private boolean performIllegal() {
        phone = getInputStr(etPhone);
        if (isPhoneMail()) {
            if(StringUtils.isEmpty(phone)){
                showToastMsg(getString(R.string.register_illegalemptyphone));
                return false;
            }
            if (!StringUtils.isTaiPhone(phone)) {
                showToastMsg(getString(R.string.register_illegalphone));
                return false;
            }
        } else {
            if(StringUtils.isEmpty(phone)){
                showToastMsg(getString(R.string.register_illegalemptyemail));
                return false;
            }
            if (!StringUtils.isEmail(phone)) {
                showToastMsg(getString(R.string.register_illegalemail));
                return false;
            }
        }
        return true;
    }

    private void verfy() {
        //if (phoneValidator.validate()) {
        if (!performIllegal()) {
            return;
        }
        ;
        showLoadingDialog("");
        //验证码
        FormResultRequest request = new FormResultRequest(UrlConstants.GETSMSVERIFICATION, codeListener, this, new TypeToken<RequestResult<FindPwdCodeBean>>() {
        }.getType());


        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
//            account
//                    accType
//            type
//                    registerSource
//            lang
        ajaxParams.putStringTypeParam("account", phone);
        //账号类型（1.手机号码 2.电子邮箱）
        ajaxParams.putCommonTypeParam("accType", mGetPhoneMail);
        //类型（注册1,找回密码2,修改密码3,优惠券4,商家审核短信下发5,快速登录6,订阅手机发送7,修改手机8,完善资料（邮箱注册添加手机号）9,修改邮箱10）
        ajaxParams.putCommonTypeParam("type", Constants.ValidateType.FORGOT_PASSWORD);

        ajaxParams.putCommonTypeParam("registerSource", Constants.RegisterSource.ANDROID);

        //ajaxParams.putStringTypeParam("lang", UIUtils.getString(R.string.common_lang));

        request.setRequestParams(ajaxParams);
        executeRequest(request);
    }

    private void next() {
        if (!performIllegal()) {
            return;
        }
        ;
        if (TextUtils.isEmpty(etVerfy.getText())) {
            showToastMsg(getString(R.string.register_empty_verfy));
            return;
        }
        if (TextUtils.isEmpty(mPwd.getText()) || TextUtils.isEmpty(mPwdAgain.getText())) {
            showToastMsg(getString(R.string.register_empty_password));
            return;
        } else if (!mPwd.getText().toString().equals(mPwdAgain.getText().toString())) {
            showToastMsg(getString(R.string.register_empty_password_again));
            return;
        }

        int tempLength = mPwd.getText().toString().trim().toCharArray().length;
        if (tempLength > 16 || tempLength < 6) {
            showToastMsg(getString(R.string.register_password_number));
            return;
        }

        showLoadingDialog("");
        FormResultRequest<FindPwdVerfyBean> request = new FormResultRequest<FindPwdVerfyBean>(UrlConstants.FINDPASSWORDCHECKCODE, verfyListener, this,
                new TypeToken<RequestResult<FindPwdVerfyBean>>() {
                }.getType());


        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putStringTypeParam("phone", phone);
        ajaxParams.putCommonTypeParam("password", MD5Security.getMd5_32_UP(mPwd.getText().toString().trim()));
        ajaxParams.putCommonTypeParam("verification", etVerfy.getText());
        // ajaxParams.putStringTypeParam("lang", UIUtils.getString(R.string.common_lang));

        request.setRequestParams(ajaxParams);
        executeRequest(request);


    }

    private Response.Listener<RequestResult> codeListener = new Response.Listener<RequestResult>() {


        @Override
        public void onResponse(RequestResult arg0) {
            dismissLoadingDialog();
            showToastMsg(arg0.msg);
            btnVerfy.setClickable(false);
            setVerfyEt(true);
            mTimeStart = new CountDownTimer(120000, 1000) {
                public void onTick(long millisUntilFinished) {
//
                    btnVerfy.setText(String.format("%s" +"S", String.valueOf(millisUntilFinished / 1000)));
                }

                public void onFinish() {
//					btnVerfy.setTextColor(getResources().getColor(R.color.color_f25522));
                    btnVerfy.setText(R.string.register_getVerification);
                    btnVerfy.setClickable(true);
                }
            }.start();
        }
    };

    private Response.Listener<RequestResult<FindPwdVerfyBean>> verfyListener = new Response.Listener<RequestResult<FindPwdVerfyBean>>() {

        @Override
        public void onResponse(RequestResult<FindPwdVerfyBean> arg0) {
            dismissLoadingDialog();
            if (arg0.flag == 1) {
//                FindPwdVerfyBean bean = arg0.getRs();
//                Intent intent = new Intent(FindPwdActivity.this, SetNewPwdActivity.class);
//                intent.putExtra("FindPwdVerfyBean", bean);
//                intent.putExtra("phone", phone);
//                showActivity(aty, intent);
                finish();
            }
            showToastMsg(arg0.msg);

        }
    };

    private void setVerfyEt(boolean isShow) {
        if (isShow) {
            etVerfy.setEnabled(true);
        } else {
            etVerfy.setEnabled(false);
        }
    }

}
